import pyautogui
import time
import pyperclip
import subprocess
import os
import pandas as pd

# 等待几秒以准备
time.sleep(2)

# 定义图像文件路径
bowser_folder = 'bowser/'  # 浏览器窗口按钮文件夹路径
redbook_folder = 'redbook/'  # 打开窗口后按钮文件夹路径

# 定义各个文件夹中的图像文件名
bowser_images = ['109.png','110.png']  # 浏览器窗口按钮图像文件名

# 定义要导航的文件夹路径
center_file = 'C:\\Users\\23863\\Desktop\\word分离出口\\广州200'

dto_file_path = center_file + '\\小红蓝字.dto'  # 需要运行的文件路径

# 定义用到的文件夹下标
count = 1

# 链接收集
copied_links = []

#所有文件夹的名称
folders = [name for name in os.listdir(center_file) if os.path.isdir(os.path.join(center_file, name))]
folders.sort()

# 定义一个函数来查找图像，并在找不到时等待并重试
def find_image_with_retry(image_path, retries=5, delay=2):
    while True:
        for attempt in range(retries):
            try:
                location = pyautogui.locateCenterOnScreen(image_path)
                if location:
                    return location
            except Exception as e:
                print(f"暂未找到按钮：{image_path}")
            time.sleep(delay)

        print("按下回车键继续...")
        input()  # 程序暂停，等待用户输入
        print("程序继续")

# 依次点击浏览器窗口按钮
for bowser_image in bowser_images:

    folder_path = center_file + '\\' + folders[count]  # 文件夹路径
    output_file_path = folder_path + '\\output.txt'  # 输出文件路径

    # 获取完整的图像路径
    bowser_image_path = os.path.join(bowser_folder, bowser_image)
    
    # 查找浏览器窗口按钮图像并获取其中心位置
    browser_button_location = find_image_with_retry(bowser_image_path)

    
    # 点击浏览器窗口按钮
    pyautogui.click(browser_button_location)
    print(f"已点击浏览器窗口按钮: {bowser_image}")
    
    # 等待窗口打开
    time.sleep(1)

    # 点击 redbook 文件夹中的 '1.png'
    redbook_image_path = os.path.join(redbook_folder, '1.png')
    redbook_button_location = find_image_with_retry(redbook_image_path)
    pyautogui.click(redbook_button_location)
    print("已点击 '1.png'")
    

    time.sleep(0.5)  # 等待页面加载完成
    
    # 点击 redbook 文件夹中的 '2.png'
    redbook_image_path = os.path.join(redbook_folder, '2.png')
    redbook_button_location = find_image_with_retry(redbook_image_path)
    pyautogui.click(redbook_button_location)
    print("已点击 '2.png'")

    
    # 点击 redbook 文件夹中的 '3.png'
    redbook_image_path = os.path.join(redbook_folder, '3.png')
    redbook_button_location = find_image_with_retry(redbook_image_path)
    pyautogui.click(redbook_button_location)
    print("已点击 '3.png'")


    # 使用剪贴板输入文件夹路径并确认
    time.sleep(0.5)  # 等待文件选择框准备好
    pyautogui.hotkey('alt', 'd')  # 聚焦到地址栏
    pyperclip.copy(folder_path)  # 复制路径到剪贴板
    pyautogui.hotkey('ctrl', 'v')  # 粘贴路径
    pyautogui.press('enter')  # 确认输入
    print(f"已输入文件夹路径并确认: {folder_path}")
    
    # 等待文件夹加载
    time.sleep(0.5)
    
    # 将焦点移至文件列表（通常可以通过 Tab 键）
    for _ in range(4):  # 根据实际情况调整 Tab 键次数
        pyautogui.press('tab')
    time.sleep(0.5)
    
    # 全选文件
    pyautogui.hotkey('ctrl', 'a')
    print("已全选文件")
    
    # 确认选择
    pyautogui.press('enter')
    print("已确认选择文件")
    
    # 等待确认选择后的界面加载
    time.sleep(0.5)
    for _ in range(2):  # 根据实际情况调整 Tab 键次数
        pyautogui.press('tab')
    time.sleep(0.5)

    # 读取 output.txt 文件的所有内容
    with open(output_file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    # 获取第一行内容
    if lines:
        first_line = lines[0].strip()
        # 将第一行内容复制到剪贴板
        pyperclip.copy(first_line)
        print(f"已复制第一行内容: {first_line}")
        time.sleep(0.5)
        # 粘贴内容（假设已聚焦到粘贴位置）
        pyautogui.hotkey('ctrl', 'v')
        print("已粘贴第一行内容")

        time.sleep(0.5)
        pyautogui.press('tab')
        print("已换行")
        
        # 获取第一行以外的内容
        remaining_lines = ''.join(lines[1:]).strip()
        if remaining_lines:
            # 将剩余内容复制到剪贴板
            pyperclip.copy(remaining_lines)
            print(f"已复制第一行以外的内容: {remaining_lines}")

            # 粘贴内容并触发快捷键
            time.sleep(0.5)
            pyautogui.hotkey('ctrl', 'v')
            print("已粘贴第一行以外的内容")
    else:
        print(f"{output_file_path} 文件为空或不存在")

    subprocess.run(['start', dto_file_path], shell=True) # 复制蓝字
    print(f"已运行文件: {dto_file_path}")

    time.sleep(0.5)
    pyautogui.hotkey('ctrl', 'v')# 粘贴蓝字3

    #  最小化
    time.sleep(0.5)
    pyautogui.hotkey('alt', 'space')
    time.sleep(0.5)
    pyautogui.press('n')

    # 等待操作完成
    time.sleep(1)
    count += 1
    print(count)

# 发布作品
for bowser_image in bowser_images:

    # 获取完整的图像路径
    bowser_image_path = os.path.join(bowser_folder, bowser_image)
    
    # 查找浏览器窗口按钮图像并获取其中心位置
    browser_button_location = find_image_with_retry(bowser_image_path)
    
    # 点击浏览器窗口按钮
    pyautogui.click(browser_button_location)
    print(f"已点击浏览器窗口按钮: {bowser_image}")

    # 准备发布
    time.sleep(0.5)
    redbook_image_path = os.path.join(redbook_folder, '4.png')
    redbook_button_location = find_image_with_retry(redbook_image_path)
    pyautogui.moveTo(redbook_button_location.x, redbook_button_location.y, duration=0)
    print(f"鼠标已移动到图像位置: ({redbook_button_location.x}, {redbook_button_location.y})")


    # time.sleep(0.5) #等待移动
    # 向下滚动
    pyautogui.scroll(-500)
    time.sleep(1)

    # 点击发布
    redbook_image_path = os.path.join(redbook_folder, '5.png')
    redbook_button_location = find_image_with_retry(redbook_image_path)
    pyautogui.click(redbook_button_location)
    print("已点击 '5.png'")


    time.sleep(1)

# 收集链接
for bowser_image in bowser_images:

    # 获取完整的图像路径
    bowser_image_path = os.path.join(bowser_folder, bowser_image)
    
    # 查找浏览器窗口按钮图像并获取其中心位置
    browser_button_location = find_image_with_retry(bowser_image_path)

    # 点击浏览器窗口按钮
    pyautogui.click(browser_button_location)
    print(f"已点击浏览器窗口按钮: {bowser_image}")


    # 点击笔记管理开始收集
    time.sleep(0.5) # 等待窗口打开
    redbook_image_path = os.path.join(redbook_folder, '6.png')
    redbook_button_location = find_image_with_retry(redbook_image_path)
    pyautogui.click(redbook_button_location)
    print(f"已点击笔记管理按钮: {bowser_image}")
    time.sleep(0.5) # 等待加载
    
    # 点击发布成功作品
    redbook_image_path = os.path.join(redbook_folder, '7.png')
    redbook_button_location = find_image_with_retry(redbook_image_path)
    pyautogui.click(redbook_button_location.x - 100, redbook_button_location.y)
    print(f"鼠标已打开作品")
    time.sleep(0.5) #等待页面加载


    # 复制作品链接
    pyautogui.hotkey('alt', 'd')
    print("聚焦链接")

    time.sleep(1)
    pyautogui.hotkey('ctrl', 'c')
    print("复制链接")

    # 获取剪贴板内容并存储
    copied_link = pyperclip.paste()
    copied_links.append(copied_link)

    print(f"已复制链接: {copied_link}")
    time.sleep(0.5)


# 处理收集到的链接并保存到Excel文件
# 定义Excel文件路径
excel_file = 'copied_links.xlsx'

# 检查文件是否存在
if os.path.exists(excel_file):
    # 如果文件存在，读取现有的链接
    existing_df = pd.read_excel(excel_file)
    existing_links = existing_df['Link'].tolist()
else:
    # 如果文件不存在，初始化为空的链接列表
    existing_links = []

# 将新链接追加到已有的链接列表中
all_links = existing_links + copied_links

# 去除重复的链接
all_links = list(set(all_links))

# 将所有链接保存到DataFrame中
df = pd.DataFrame(all_links, columns=['Link'])

# 将DataFrame保存到Excel文件
df.to_excel(excel_file, index=False)
print(f"已保存收集的链接到 '{excel_file}'")
